package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.LikesBehaviorDto;
import com.heima.behavior.pojos.ApLikesBehavior;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author Gareth Cao
 * @date 2022/6/25 11:41
 */
@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 用户点赞行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //1 校验参数
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2 获取用户登录id
        ApUser apUser = ApThreadLocalUtil.getUser();
        if (apUser == null) {
            //未登录
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (apUser.getId() == 0) {
            //游客登录
            return ResponseResult.errorResult(AppHttpCodeEnum.VISITOR_NEED_LOGIN);
        }
        //3 查询用户是否已经点赞
        //3.1 定义点赞行为的key,hash存储数据，大key为文章id，小key为用户id
        String likes_key = "USER_LIKES_" + dto.getArticleId();
        //3.2 从redis当中查出是否包含key
        Boolean flag = stringRedisTemplate.opsForHash().hasKey(likes_key, apUser.getId() + "");
        //4 如果已经点赞，并正在执行点赞操作，那么直接返回
        if (flag && dto.getOperation() == 0) {
            return ResponseResult.okResult(AppHttpCodeEnum.LIKE_EXIST);
        }
        //5 如果已经点赞了，并执行取消操作，则删除redis和mongo
        if (flag && dto.getOperation() == 1) {
            //删除redis
            stringRedisTemplate.opsForHash().delete(likes_key, apUser.getId() + "");
            //删除mongo
            Query query = Query.query(Criteria.where("userId").is(apUser.getId())
                    .and("articleId").is(dto.getArticleId()));
            mongoTemplate.remove(query, ApLikesBehavior.class);
            return ResponseResult.okResult(AppHttpCodeEnum.LIKE_CANCEL);
        }
        //6 未点赞并执行点赞操作，则添加redis和mongo
        if (!flag && dto.getOperation() == 0) {
            //添加redis
            stringRedisTemplate.opsForHash().put(likes_key, apUser.getId() + "", "1");
            //添加mongo
            ApLikesBehavior apLikesBehavior = new ApLikesBehavior();
            apLikesBehavior.setId(ObjectId.get().toHexString());
            apLikesBehavior.setUserId(apUser.getId().longValue());
            apLikesBehavior.setArticleId(dto.getArticleId());
            apLikesBehavior.setType((short) 0);
            apLikesBehavior.setCreatedTime(new Date());
            mongoTemplate.insert(apLikesBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.LIKE_SUCCESS);
        }
        return null;
    }
}
